package game.states
{
	
	/**
	 * ...
	 * @author Kirill Pletnev
	 */
	public class StateMachine
	{
		protected var _game:Game;
		protected var _currentState:StateBase;
		protected var _nextState:StateBase;
		
		public function StateMachine(game:Game)
		{
			_game = game;
		}
		
		public function get game():Game
		{
			return _game;
		}
		
		public function get currentState():StateBase
		{
			return _currentState;
		}
		
		public function changeState(nextState:StateBase):void
		{
			_nextState = nextState;
		}
		
		public function switchNextState():void
		{
			if (_nextState != null)
			{
				if (_currentState != null)
				{
					trace("======= END STATE: " + _currentState);
					_currentState.end();
					_currentState = null;
				}
				
				_currentState = _nextState;
				_nextState = null;
				
				if (_currentState != null)
				{
					trace("======= START STATE: " + _currentState);
					_currentState.start();
				}
			}
		}
		
		public function update():void
		{
			if (_nextState != null)
			{
				switchNextState();
			}
			
			if (_currentState != null)
			{
				_currentState.update();
			}
		}
	}
}